using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using YouTube.API;

namespace SimpleVideo
{
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                try
                {
                    string devId = ConfigurationManager.AppSettings["DeveloperID"];
                    YouTubeService youTube = new YouTubeService();

                    YouTube.API.VideoDetails.UTResponse resultSet = youTube.VideosGetDetails(devId, Request.QueryString["id"]);

                    YouTube.API.VideoDetails.VideoDetails vid = resultSet.videoDetails;

                    mainRating.Visible = true;

                    mainDescription.InnerText = vid.description;
                    mainTitle.InnerText = vid.title;
                    mainRating.CurrentRating = (int)(3 * vid.rating_avg);

                    mainMovie.Controls.Clear();

                    Control uc;
                    Type ucType;
                    PropertyInfo ucType_TextValue;

                    uc = LoadControl("MovieControl.ascx");

                    ucType = uc.GetType();

                    ucType_TextValue = ucType.GetProperty("MovieUrl");
                    ucType_TextValue.SetValue(uc, "http://www.youtube.com/v/"+ Request.QueryString["id"], BindingFlags.SetProperty, null, null, null);

                    mainMovie.Controls.Add(uc);

                }
                catch (Exception)
                {
                    mainRating.Visible = false;
                    mainMovie.Controls.Clear();
                    mainDescription.InnerText = string.Empty;
                    mainTitle.InnerText = string.Empty;
                }
            }
            else
            {
                mainRating.Visible = false;
                mainMovie.Controls.Clear();
                mainDescription.InnerText = string.Empty;
                mainTitle.InnerText = string.Empty;
            }

            try
            {
                if (Session["movies"] != null)
                {
                    YouTube.API.VideoList.video[] videos = Session["movies"] as YouTube.API.VideoList.video[];
                    
                    BindVideosFromList(videos);
                }                
            }
            catch (Exception)
            {
            }
            
        }

        /// <summary>
        /// Handles the ServerClick event of the searchsubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void searchsubmit_ServerClick(object sender, EventArgs e)
        {
            Session["text"] = searchinput.Value;

            SearchVideos(1);
        }

        /// <summary>
        /// Searches the videos.
        /// </summary>
        /// <param name="pageIndex">Index of the page.</param>
        private void SearchVideos(int pageIndex)
        {
            try
            {
                string devId = ConfigurationManager.AppSettings["DeveloperID"];
                YouTubeService youTube = new YouTubeService();

                YouTube.API.VideoList.UTResponse resultSet = youTube.VideosListByTag(devId, Session["text"].ToString(), pageIndex, 5);

                YouTube.API.VideoList.video[] videos = resultSet.video_list;

                if (videos.Length == 0 && pageIndex > 1)
                {
                    SearchVideos(pageIndex - 1);
                }

                BindVideosFromList(videos);

                Session["movies"] = videos;
                Session["page"] = pageIndex;
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        /// <summary>
        /// Binds the videos from list.
        /// </summary>
        /// <param name="videos">The videos.</param>
        private void BindVideosFromList(YouTube.API.VideoList.video[] videos)
        {
            resultList.Controls.Clear();

            Control uc;
            Type ucType;
            PropertyInfo ucType_TextValue;

            foreach (YouTube.API.VideoList.video vid in videos)
            {
                uc = LoadControl("SearchResult.ascx");

                ucType = uc.GetType();

                ucType_TextValue = ucType.GetProperty("Date");
                ucType_TextValue.SetValue(uc, vid.title, BindingFlags.SetProperty, null, null, null);

                ucType_TextValue = ucType.GetProperty("Link");
                ucType_TextValue.SetValue(uc, vid.id, BindingFlags.SetProperty, null, null, null);

                ucType_TextValue = ucType.GetProperty("Description");
                ucType_TextValue.SetValue(uc, "view >>", BindingFlags.SetProperty, null, null, null);

                ucType_TextValue = ucType.GetProperty("Rating");
                ucType_TextValue.SetValue(uc, vid.ratingavg, BindingFlags.SetProperty, null, null, null);

                ucType_TextValue = ucType.GetProperty("ImageUrl");
                ucType_TextValue.SetValue(uc, vid.thumbnailUrl, BindingFlags.SetProperty, null, null, null);

                
                resultList.Controls.Add(uc);
            }            
        }

        /// <summary>
        /// Handles the Click event of the previous control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void previous_Click(object sender, EventArgs e)
        {
            if (Session["page"] != null)
            {
                int page;
                int.TryParse(Session["page"].ToString(), out page);

                if (page == 0)
                {
                    SearchVideos(1);
                }
                else if (page == 1)
                {
                    //do nothing
                }
                else
                {
                    SearchVideos(page - 1);
                }

            }
        }

        /// <summary>
        /// Handles the Click event of the next control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void next_Click(object sender, EventArgs e)
        {
            if (Session["page"] != null)
            {
                int page;
                int.TryParse(Session["page"].ToString(), out page);
                
                SearchVideos(page + 1);
            }
        }
    }
}
